#include "AliyunLLMClient.h"
#include <QNetworkRequest>
#include <QUrlQuery>
#include <QSettings>
#include <QDebug>
#include <QSslSocket>
#include <QNetworkReply>


AliyunLLMClient::AliyunLLMClient(QObject *parent)
    : QObject(parent)
    , m_networkManager(new QNetworkAccessManager(this))
{

//    qDebug() << "QSslSocket=" << QSslSocket::sslLibraryBuildVersionString();
//    qDebug() << "SSL支持状态：" << QSslSocket::supportsSsl();
    // 从环境变量或者配置文件中读取API密钥
    QByteArray apiKeyEnv = qgetenv("DASHSCOPE_API_KEY");
    if (!apiKeyEnv.isEmpty()) {
        m_apiKey = QString::fromUtf8(apiKeyEnv);
    } else {
        // 或者从配置文件中读取
        QSettings settings("YourCompany", "YourApp");
        m_apiKey = settings.value("aliyun/api_key").toString();
    }

    connect(m_networkManager, &QNetworkAccessManager::finished,
            this, &AliyunLLMClient::handleNetworkReply);
}

AliyunLLMClient::~AliyunLLMClient()
{
}

void AliyunLLMClient::sendRequest(const QString &text, const QString &imageUrl)
{
    if (m_apiKey.isEmpty()) {
        emit errorOccurred("API Key is not set");
        return;
    }

           QNetworkRequest request;
           request.setUrl(QUrl("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"));

           // 设置请求头
           request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
           request.setRawHeader("Authorization", QString("Bearer %1").arg(m_apiKey).toUtf8());

           // 构建请求体
           QJsonObject contentObj1;
           contentObj1["type"] = "text";
           contentObj1["text"] = text;

           QJsonObject imageUrlObj;
           imageUrlObj["url"] = imageUrl;

           QJsonObject contentObj2;
           contentObj2["type"] = "image_url";
           contentObj2["image_url"] = imageUrlObj;

           QJsonArray contentArray;
           contentArray.append(contentObj1);
           contentArray.append(contentObj2);

           QJsonObject messageObj;
           messageObj["role"] = "user";
           messageObj["content"] = contentArray;

           QJsonArray messagesArray;
           messagesArray.append(messageObj);

           QJsonObject requestObj;
           requestObj["model"] ="qwen-vl-plus-2025-01-25";
           requestObj["messages"] = messagesArray;

           QJsonDocument jsonDoc(requestObj);
           QByteArray requestData = jsonDoc.toJson();

           // 发送POST请求
           QNetworkReply *reply = m_networkManager->post(request, requestData);

           // 连接信号槽来处理响应
           connect(reply, &QNetworkReply::finished, [=]() {
               if (reply->error() == QNetworkReply::NoError) {
                   // 读取响应
                   QByteArray responseData = reply->readAll();
                   QJsonDocument jsonResponse = QJsonDocument::fromJson(responseData);
                   qDebug() << "API Response:";
                   qDebug() << jsonResponse.toJson(QJsonDocument::Indented);

                   // 这里可以解析jsonResponse来获取模型的输出
                   // 例如:
                   // if (jsonResponse.isObject()) {
                   //     QJsonObject responseObj = jsonResponse.object();
                   //     // 解析响应...
                   // }
               } else {
                   qDebug() << "Error:" << reply->errorString();
                   qDebug() << "Response:" << reply->readAll();
               }

               reply->deleteLater();
           });






//    QNetworkRequest request;
//    request.setUrl(QUrl("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"));
//    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
//    request.setRawHeader("Authorization", QString("Bearer %1").arg(m_apiKey).toUtf8());

//    QJsonObject jsonObj;
//    jsonObj["model"] = "qwen-vl-plus-2025-01-25";

//    QJsonArray messages;
//    QJsonObject message;
//    message["role"] = "user";

//    QJsonArray contentArray;

//    // 添加文本内容
//    QJsonObject textContent;
//    textContent["type"] = "text";
//    textContent["text"] = text;
//    contentArray.append(textContent);

//    // 如果提供了图片URL，添加图片内容
//    if (!imageUrl.isEmpty()) {
//        QJsonObject imageContent;
//        imageContent["type"] = "image_url";

//        QJsonObject imageUrlObj;
//        imageUrlObj["url"] = imageUrl;

//        imageContent["image_url"] = imageUrlObj;
//        contentArray.append(imageContent);
//    }

//    message["content"] = contentArray;
//    messages.append(message);
//    jsonObj["messages"] = messages;

//    QJsonDocument doc(jsonObj);
//    QByteArray jsonData = doc.toJson();

//    m_networkManager->post(request, jsonData);
}

void AliyunLLMClient::handleNetworkReply(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray responseData = reply->readAll();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);

        if (!jsonDoc.isNull() && jsonDoc.isObject()) {
            QJsonObject jsonObj = jsonDoc.object();
            if (jsonObj.contains("choices") && jsonObj["choices"].isArray()) {
                QJsonArray choices = jsonObj["choices"].toArray();
                if (!choices.isEmpty() && choices[0].isObject()) {
                    QJsonObject choice = choices[0].toObject();
                    if (choice.contains("message") && choice["message"].isObject()) {
                        QJsonObject message = choice["message"].toObject();
                        if (message.contains("content")) {
                            QString content = message["content"].toString();
                            emit responseReceived(content);
                        }
                    }
                }
            }
        } else {
            emit errorOccurred("Invalid JSON response");
        }
    } else {
        emit errorOccurred(reply->errorString());
    }

    reply->deleteLater();
}
